﻿
namespace Microsoft.Dynamics.AX.Framework.TeamFoundationServerFacade
{
    using System;
    using Microsoft.TeamFoundation.Client;
    using System.Net;

    /// <summary>
    /// A proxy class for TFS connection.
    /// Holds access to TeamProjectCollection.
    /// </summary>
    [Serializable]
    public class ConnectionManagerProxy
    {
        /// <summary>
        /// The name of the Team Project
        /// </summary>
        public string ProjectName
        {
            get;
            private set;
        }

        /// <summary>
        /// Team Project Collection
        /// </summary>
        internal TfsTeamProjectCollection TeamProjectCollection
        {
            get;
            private set;
        }
        
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="teamFoundationServerName">Server URL</param>
        /// <param name="projectName">The name of the project in Team Project Collection specified by the teamFoundationServerName</param>
        public ConnectionManagerProxy(string teamFoundationServerName, string projectName)
        {
            if (String.IsNullOrEmpty(teamFoundationServerName))
                throw new ArgumentNullException("teamFoundationServerName");

            if (String.IsNullOrEmpty(projectName))
                throw new ArgumentNullException("projectName");

            SysVersionControlParameters globalParams = SysVersionControlParameters.find();

            if (globalParams.VCSType == SysVersionControlType.SysVersionControlVSO)
            {
                NetworkCredential netCred = new NetworkCredential(globalParams.SysVersionControlVSO_UserName, globalParams.SysVersionControlVSO_Password);
                BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
                TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);

                // tfs setup
                this.TeamProjectCollection = new TfsTeamProjectCollection(new Uri(teamFoundationServerName), tfsCred);
                this.TeamProjectCollection.EnsureAuthenticated();

                if (this.TeamProjectCollection.InstanceId != Guid.Empty)
                {
                    Global.info("Connected to Visual Studio Online");
                }
            }
            else
            {
                this.TeamProjectCollection = new TfsTeamProjectCollection(new Uri(teamFoundationServerName), new UICredentialsProvider());
                this.TeamProjectCollection.EnsureAuthenticated();
            }

            this.ProjectName = projectName;
        }
    }
}
